<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="活动方式">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="内容详情">
        <quillEditor
          :options="editorOption"
          v-model="form.content"
          ref="editorComp"
        ></quillEditor>
      </el-form-item>
      <el-dialog
        title="指标信息"
        :visible.sync="showMetric"
        width="600px"
        append-to-body
      >
        <el-button @click="handleClick()">插入</el-button>
      </el-dialog>
    </el-form>
  </div>
</template>
<script>
import { quillEditor } from "vue-quill-editor";
import Delta from "quill-delta";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

export default {
  components: {
    quillEditor
  },
  mounted() {
    this.initButton();
  },
  data() {
    return {
      form: {
        name: "",
        content: ""
      },
      showMetric: false,
      quill_this: this,
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote"],
              ["clean"],
              ["insertMetric"] // 新添加的工具
            ],
            handlers: {
              shadeBox: null,
              that: this,
              insertMetric: function() {
                const self = this.handlers.that;
                console.log(self.form.name);
                self.showMetric = true;
                // 获取window的this
                self.quill_this = this;
              }
            }
          }
        }
      }
    };
  },
  methods: {
    handleClick() {
      const info = {
        title: "123",
        content:
          "https://workstation.chinaeast2.cloudapp.chinacloudapi.cn:8099/ecomimage/maintain/2021/08/03/d3dfdac5fd674c8484d58155c887de56ep467lpqur.jpg"
      };
      this.insert(info);
      this.showMetric = false;
    },
    insert(info) {
      console.log(info);
      const quill_this = this.quill_this;
      // editor自带方法：获取当前鼠标位置
      const range = quill_this.quill.getSelection(true);
      // 插入内容
      // let insert_value = "${" + info.title + "}";
      const insert_value = `${info.title}${info.content}`;
      // editor自带方法：插入内容，更新页面元素，updateContents的第一个参数为Delta，需要引入
      quill_this.quill.updateContents(
        new Delta()
          .retain(range.index)
          .delete(range.length)
          .insert(insert_value)
      );
      quill_this.quill.setSelection(range.index + insert_value.length);
    },

    initButton() {
      const sourceEditorButton = document.querySelector(".ql-insertMetric");
      sourceEditorButton.innerHTML =
        '<i class="el-icon-plus" style="font-size: 18px;color: black"></i>';
    }
  }
};
</script>
